package com.lindroy.androidplayer.utils

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lindroy.androidplayer.constant.MAX_SEARCH_HISTORY_SIZE
import com.tencent.mmkv.MMKV

/**
 * @author Lin
 * @date 2022/3/10
 * @function
 */
object KVUtil {
    private val kvAppData = MMKV.mmkvWithID("app_data")

    private const val KEY_SEARCH_HISTORY = "search_history"

    val searchHistory: List<String>
        get() = kvAppData.decodeString(KEY_SEARCH_HISTORY)?.let {
            Gson().fromJson(it, object : TypeToken<List<String>>() {}.type)
        } ?: listOf()

    fun setSearchHistory(list: List<String>) {
        kvAppData.encode(
            KEY_SEARCH_HISTORY, Gson().toJson(
                if (list.size >= MAX_SEARCH_HISTORY_SIZE) {
                    list.subList(0, MAX_SEARCH_HISTORY_SIZE)
                } else list
            )
        )
    }

    fun addSearchHistory(keyword: String) {
        val historyData = arrayListOf<String>().apply {
            addAll(searchHistory)
        }
        if (historyData.contains(keyword)) {
            historyData.remove(keyword)
        }
        historyData.add(0, keyword)
        setSearchHistory(historyData)
    }

    fun removeSearchHistory(keyword: String): Boolean {
        val historyData = arrayListOf<String>().apply {
            addAll(searchHistory)
        }
        if (historyData.remove(keyword)) {
            setSearchHistory(historyData)
            return true
        }
        return false
    }

}